package com.ballcat.spring.cloud.learning.controller;

import com.ballcat.spring.cloud.learning.common.CommonResult;
import com.ballcat.spring.cloud.learning.entity.Payment;
import com.ballcat.spring.cloud.learning.service.PaymentService;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * @author pengshun
 * @date 2022-04-04 17:33
 * @description
 */
@Slf4j
@RestController
@RequestMapping("/payment")
@AllArgsConstructor
public class PaymentController {

    private final PaymentService paymentService;

    private final DiscoveryClient discoveryClient;

    @PostMapping(value = "save")
    public CommonResult<Integer> save(@RequestBody Payment payment) {
        return CommonResult.ok(paymentService.save(payment));
    }

    @GetMapping(value = "getById")
    public CommonResult<Payment> getById(@RequestParam Integer id) {
        return CommonResult.ok(paymentService.getById(id), "访问8001");
    }

    @GetMapping(value = "discovery")
    public Object discovery() {
        List<String> services = discoveryClient.getServices();
        for (String service : services) {
            log.info("已注册的服务有: {}", service);
        }
        List<ServiceInstance> instances = discoveryClient.getInstances("CLOUD-PAYMENT-SERVICE");
        for (ServiceInstance instance : instances) {
            log.info("CLOUD-PAYMENT-SERVICE, ID: {}, HOST:{}, PORT: {}, URI: {}, METADATA: {}", instance.getInstanceId(), instance.getHost(), instance.getPort(), instance.getUri(), instance.getMetadata());
        }
        return discoveryClient;
    }
}
